package kassiopeia.plugin.generator;

import java.util.concurrent.TimeUnit;

import kassiopeia.plugin.DataProviderPlugin;
import kassiopeia.plugin.Event;

import org.apache.log4j.Logger;

public class EventGeneratorPlugin extends DataProviderPlugin {

	private Logger log = Logger.getLogger(EventGeneratorPlugin.class);
	
	private static final String EPS_PARAMETER_NAME = "eps";
	private static final String OUTPUT = "out";
	
	private int EPS;
	
	@Override
	public void beforeTask() {
		log.info("Configuration of EventGeneratorPlugin started");
		try {
			EPS = Integer.parseInt(getContext().getParameter(EPS_PARAMETER_NAME));
		} catch (RuntimeException ex) {
			throw new RuntimeException("EventGeneratorPlugin configuration error", ex);
		}
		log.info("Configuration of EventGeneratorPlugin finished");
	}
	
	@Override
	public void afterTask() {
		log.info("EventGeneratrPlugin finished work");
	}

	@Override
	public void provideData() {
		boolean doRun = true;
		int iterationCounter = 0;
		
		while (doRun) {
			Event event = new Event("EventGeneratorPlugin:" + getContext().getPluginInstanceId() + ":" + getContext().getThisAgentId());
			for (int i = 0; i < EPS; i++) {
				send(event);
			}
			
			if (iterationCounter == 60) {
				EPS = 5;
				log.info("EPS = 5");
			}
			if (iterationCounter == 120) {
				EPS = 10;
				log.info("EPS = 10");
			}
			if (iterationCounter == 180) {
				EPS = 20;
				log.info("EPS = 20");
			}
			if (iterationCounter == 240) {
				EPS = 40;
				log.info("EPS = 40");
			}
			if (iterationCounter == 300) {
				EPS = 20;
				log.info("EPS = 20");
			}
			if (iterationCounter == 360) {
				EPS = 10;
				log.info("EPS = 10");
			}
			if (iterationCounter == 420) {
				EPS = 5;
				log.info("EPS = 5");
			}
			if (iterationCounter == 480) {
				EPS = 1;
				log.info("EPS = 1");
			}
			if (iterationCounter == 540) {
				doRun = false;
				log.info("EPS = 0");
			}
			iterationCounter++;
			sleep();
		}
	}
	
	private void send(Event event) {
		getContext().send(event, OUTPUT);
	}
	
	private void sleep() {
		try {
			TimeUnit.SECONDS.sleep(1L);
		} catch (InterruptedException e) {
			log.warn("Error during sleep for EventGeneratorPlugin " + getContext().getPluginInstanceId(), e);
		}
	}

}
